var mainPlayer = new Vue({
    el:'#mainPlayer',
    data:{
        currentSong:null,
        playList:[],

        songImg:'',
        songSrc:'',
        isPlaying:false,
        isLike:false,

        mainAudio:null,

        progressPercent:0,
        listPosition:0,
        isRepeat:false,

        timelyric:[],

        preLyric:[],
        nowLyric:null,
        sufLyric:[]
    },
    methods:{
        // 初始化
        init:function () {
            // 获取请求的歌曲
            $.get('/song/current/id',function (cid) {
                $.get('/song/get/'+cid,function (song) {
                    mainPlayer.currentSong = song;
                    mainPlayer.getIsLike();
                    console.log('cu '+mainPlayer.currentSong['pk']);
                    mainPlayer.mainAudio = new Audio();
                    mainPlayer.mainAudio.preload = "auto";
                    mainPlayer.mainAudio.ontimeupdate = mainPlayer.updateProgress;
                    mainPlayer.mainAudio.onended = mainPlayer.endedSong;
                    mainPlayer.play();
                });
            });
            // 获取播放列表
            $.get('/song/playlist',function (s) {
                mainPlayer.playList = s;
                mainPlayer.playList.forEach(s=>console.log(s.name));
            });

        },
        // 判断是否收藏歌曲
        getIsLike:function () {
            $.get('/song/is-like/'+this.currentSong.pk,function (result) {
                // console.log(result);
                mainPlayer.isLike = result['result'] == 'yes' ? true : false;
            });
        },
        // 播放歌曲
        play:function () {
            console.log("play:  "+mainPlayer.currentSong['pk']);
            this.mainAudio.src = mainPlayer.currentSong['fileUri'];
            this.songImg = this.currentSong.imgUri;
            this.isPlaying = true;
            this.mainAudio.play();
            this.lyricDecode();
        },
        // 暂停
        pause:function () {
            if (this.isPlaying) {
                this.mainAudio.pause();
            }else {
                this.mainAudio.play();
            }
            this.isPlaying = ! this.isPlaying;
        },
        // 更新进度条
        updateProgress:function () {
            var total = this.mainAudio.duration;
            var now = this.mainAudio.currentTime;
            this.progressPercent = now/total * 100;

            // 歌词滚动
            this.updateLyric();
        },
        // 切歌
        changeSong:function (direction) {
            // console.log(direction+mainPlayer.listPosition);
            if (direction=='>'){
                mainPlayer.listPosition++;
                if (mainPlayer.listPosition > mainPlayer.playList.length - 1) {
                    mainPlayer.listPosition = 0;
                }
            }else if (direction == '<') {
                mainPlayer.listPosition -- ;
                if (mainPlayer.listPosition < 0) {
                    mainPlayer.listPosition = mainPlayer.playList.length-1;
                }
            }
            mainPlayer.currentSong = mainPlayer.playList[mainPlayer.listPosition];
            mainPlayer.mainAudio.pause();
            mainPlayer.play();
            // 评论
            commentObject.currentSongId = mainPlayer.currentSong.pk;
            commentObject.getComments(mainPlayer.currentSong.pk);
        },

        // 收藏
        like:function () {
            // console.log('liking ------>'+this.currentSong.pk);
            $.get('/song/like/'+this.currentSong.pk,function (result) {
                if (result['result'] == 'done'){
                    mainPlayer.isLike = true;
                }else if (result['result'] == 'permission error') {
                    alert('没登陆不能收藏');
                }
            });
        },
        // 取消收藏
        dislike:function () {
            // console.log('disliking ------>'+this.currentSong.pk);
            $.get('/song/dislike/'+this.currentSong.pk,function (result) {
                if (result['result'] == 'done'){
                    mainPlayer.isLike = false;
                }else {
                    alert(result['result']);
                }
            });
        },
        endedSong:function () {
            if (this.isRepeat) {
                this.mainAudio.currentTime = 0;
                this.mainAudio.pause();
                this.mainAudio.play();
            }else {
                this.changeSong(">");
            }
        },
        // 循环设置
        repeatChange:function () {
            this.isRepeat = ! this.isRepeat;
        },
        // 声音大小
        changeVol:function (direction) {
            if (direction == 'up') {
                if (mainPlayer.mainAudio.volume + 0.2 > 1) {
                    mainPlayer.mainAudio.volume = 1;
                }else {
                    mainPlayer.mainAudio.volume += 0.2;
                }
            }else if (direction == 'down') {
                if (mainPlayer.mainAudio.volume - 0.2 < 0){
                    mainPlayer.mainAudio.volume = 0;
                }else {
                    mainPlayer.mainAudio.volume -= 0.2;
                }
            }
        },
        // 进度条跳
        jump:function (event) {
            var rect = document.getElementsByClassName('progress')[0].getBoundingClientRect();
            var percent = (event.clientX - rect.left) / rect.width;
            // console.log(percent);
            mainPlayer.mainAudio.currentTime = percent * this.mainAudio.duration;
        },
        // 歌词解析
        lyricDecode:function () {
            this.timelyric = [{lyc:'',mil:0}];
            // console.log('decoding lyric...');
            _regTime = /\[\d+:\d+(\.\d+)?\]/g;
            var timeStamps = this.currentSong.lyric.match(_regTime);
            if (timeStamps) {
                for (var i = 0; i <= timeStamps.length - 2; i++) {
                    var pre = timeStamps[i];
                    var next = timeStamps[i+1];
                    var preP = this.currentSong.lyric.indexOf(pre);
                    var nextP = this.currentSong.lyric.indexOf(next);
                    var lyc = this.currentSong.lyric.slice(preP+pre.length,nextP);
                    lyc = lyc.replace('\n','');

                    var timeStr = pre.substring(1,pre.length-1);
                    var min = parseInt(timeStr.split(':')[0]);
                    var sec = parseInt(timeStr.split(':')[1].split('.')[0]);
                    var mil = parseInt(timeStr.split(':')[1].split('.')[1]);
                    var totalMil = (min * 60 + sec )*1000 + mil;
                    
                    this.timelyric.push({
                        mil:totalMil,
                        lyc:lyc,
                        index:i
                    });
                }
            }
        },
        // 歌词滚动
        updateLyric:function () {
            this.preLyric = [];
            this.nowLyric = null;
            this.sufLyric = [];

            var time = this.mainAudio.currentTime * 1000;

            var pos = 0;
            for (var i = 0; i < this.timelyric.length; i++) {
                if (time - this.timelyric[i].mil - 2000 <= 0){
                    pos = i;
                    break;
                }
            }
            this.preLyric = this.timelyric.slice(pos-4,pos);
            this.nowLyric = this.timelyric[pos];
            this.sufLyric = this.timelyric.slice(pos+1,pos+4);
        }
},
    mounted:function () {
        this.init();
    }
});
// 登录
var loginModel = new Vue({
    el: '#loginModel',
    data: {
        num: "",
        pwd: "",
        isFailed: false,
        hiddenSpan: true,
        warning: '登录失败'
    },
    methods: {
        login: function () {
            loginData = {
                number: loginModel.num,
                password: loginModel.pwd
            }
            $.post('/login', loginData, function (result) {
                switch (result['result']) {
                    case 'success':
                        location.href = '/';
                        break;
                    case 'failed':
                        loginModel.hiddenSpan = false;
                        loginModel.isFailed = true;
                        break;
                    default:
                        break;
                }
            });
        }
    }
});
// 评论
var commentObject = new Vue({
    el:"#commentObject",
    data:{
        comments:[],
        postContent:'',
        currentSongId: 0,
    },
    mounted:function () {
        this.init();
    },
    methods:{
        init:function () {
            $.get('/song/current/id',function (id) {
                $.get('/song/get/'+id,function (song) {
                    commentObject.currentSongId = song.pk;
                    commentObject.getComments(song.pk);
                });
            });
        },
        getComments:function (musicId) {
            var url = "/comments/song/"+musicId;
            $.get(url,function (comments) {
                comments.forEach(function (comment) {
                    comment['publish'] = new Date(comment['publish']).toDateString();
                });
                commentObject.comments = comments;
            });
        },
        publishComment:function () {
            var data = {
                content : commentObject.postContent,
                song: commentObject.currentSongId
            };
            var url = "/comment/add";
            $.post(url,data,function (result) {
                if (result['result'] == 'succeed'){
                    result['comment'].publish = new Date(result['comment'].publish).toDateString()
                    commentObject.comments.push(result['comment']);
                }else {
                    alert(result['result']);
                }
            });
        }
    }
});